#include <SPI.h>        
#include <Ethernet.h>
#include <EthernetUdp.h>        
/********************UDP网络部分**********************/
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
IPAddress ip(169, 254, 225, 100);         //UDP服务器IP地址
unsigned int localPort = 8888;             //服务器监听端口
char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; //接收缓冲区
char received_data[] = "received_data";    //接收数据成功后向服务器发送的字符
char finished_action[] = "finished_action";//动作完成后向服务器发送的字符
int packetSize=0;                          //数据大小
EthernetUDP Udp;                           //定义一个UDP对象
/******************************************************/
/********************数据解析部分**********************/
unsigned int numdata[2] = {0};                      //拆分后的数字数组
/******************************************************/
/********************动作执行部分**********************/

/******************************************************/


void setup() {
  //初始化网络和UDP链接
  Ethernet.begin(mac, ip);
  Udp.begin(localPort);
  //开始串口
  Serial.begin(9600);
}

void loop() 
{
  packetSize = Udp.parsePacket(); //读取数据缓冲区信息长度到packetSize
  if (packetSize)                     //如果数据缓冲区有数据
  {
    print_packetsize();
    print_ip();
    print_port();
    receivedata();   //读数据到数据缓冲区packetBuffer
    sendtoserver(received_data);
    /***********执行动作************/
    sendtoserver(packetBuffer);
    data_parsing();
    delay(1000);
    /*******************************/
    sendtoserver("End");
    Serial.println();
  }
  delay(10);
}//此处loop()主函数结束

/***************数据解析函数*****************/
void data_parsing()
{
    int j = 0;
    for(int i = 0; i < String(packetBuffer).length() ; i++)
    {
        if(packetBuffer[i] == ',')
        {
            j++;
        }
        else
        {
            numdata[j] = numdata[j] * 10 + (packetBuffer[i] - '0');
        }
    }
    for(int i = 0; i <j+1; i++)
    {
      Serial.print("data ");
      Serial.print(i);
      Serial.print(" = ");
      Serial.println(numdata[i]);
      numdata[i] = 0;
    }
    //comdata = String("");                   //清空comdata  
}
/***************UDP网络函数******************/
void receivedata()
{
    Udp.read(packetBuffer, UDP_TX_PACKET_MAX_SIZE);
    Serial.print("The information is :");
    Serial.println(packetBuffer);  
}
void sendtoserver(char send_data[])
{
    Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
    Udp.write(send_data);
    Udp.endPacket();      
}
void print_packetsize()
{
    Serial.print("The packet size is: ");
    Serial.println(packetSize);  
}
void print_port()
{
    Serial.print("The port is :");
    Serial.println(Udp.remotePort());  
}
void print_ip()
{
    IPAddress remote = Udp.remoteIP();
    Serial.print("The information from :");
    for (int i = 0; i < 4; i++)
    {
      Serial.print(remote[i], DEC);
      if (i < 3)
      {
        Serial.print(".");
      }
    }
    Serial.println();  
}

